#!/bin/bash
# vim: set tabstop=4 shiftwidth=4 expandtab:

if [ "$DEBUG" == "1" ]; then
    set -x
fi

# setup proper environment
# the hook scripts have no locale set!
export LANG=C LC_ALL=C PATH=/bin:/usr/bin

REPOS="$1"
REV="$2"

# who am I
SCRIPT=$(readlink -f $0)
SCRIPTPATH=$(dirname $SCRIPT)

# let commands be overridable for tests
SVN_CMD=${SVN_CMD:svn}
SVNLOOK_CMD=${SVNLOOK_CMD:svnlook}
MKTEMP_CMD=${MKTEMP_CMD:mktemp}

function log {
	logger -t "$0" "$@"
	echo "$@"
}

function die {
	logger -s -t "$0" "ERROR: $@"
	exit 1
}

# Read configuration file either from *local* development config or from *svn repo* production conf
if [ -r "./config-rpm-maker.conf.development" ]; then
  source "./config-rpm-maker.conf.development"
elif [ -r "$REPOS/hooks/config_rpm_maker.conf" ]; then
  source "$REPOS/hooks/config_rpm_maker.conf"
else
  die "Could not source configuration file"
fi

# Append the content of a given file $2 to the given variable $1 (by name! magic :)
# IN
#   $1 the name of the global variable to append to
#   $2 the full qualified file's content to append to $1
function concatDependencies() {
	local dep_ref=$1
	eval dep_value=\$$1
	local FILE=$2
    [[ -r "$FILE" ]] && eval "$dep_ref='$dep_value
$(< $FILE)'"
    
}


log starting "$REPOS" "$REV"

# null globbing makes unfulfilled patterns disappear
shopt -s nullglob

# make sure that our result is group writable
umask 0002

#set -x

#retrieve the directories that changed from the svn
DIRS_CHANGED=()
while read -r ; do
	h=${REPLY:4}
	h=${h%/*}
	[ -z "$h" ] && continue
	DIRS_CHANGED=( "${DIRS_CHANGED[@]}" "$h" )
done < <(
	$SVNLOOK_CMD changed "$REPOS" --revision "$REV"
)

#retrieve the complete host list of hosts which are declared in the svn
ALL_HOSTS="$(
	$SVNLOOK_CMD tree -N --full-paths "$REPOS" config/host --revision "$REV" | while read -r ; do
		h=${REPLY##config/host/}
		h=${h%%/*}
		[ -z "$h" ] && continue
		echo "$h"
	done
)"

#translate the DIRS_CHANGED into a PATTERN which can be used to filter ALL_HOSTS
#
#Example:
#PATTERN='^...web[0-9a-f]+$
#^gibnix09$'
PATTERN=""
for d in "${DIRS_CHANGED[@]}" ; do
	# go over the changed dirs
	PAT=""
	# process "all" changes
	if [[ "$d" = config/all/* ]] ; then
		PATTERN=".*" # thake all hosts
		break
	fi
	# process "host" changes
	if [[ "$d" = config/host/* ]] ; then
		h="${d##config/host/}" # read host name into $h
		h="${h%%/*}"
		PAT="^$h$" # patternize
	fi
	# process "typ" changes
	if [[ "$d" = config/typ/* ]] ; then
		h="${d##config/typ/}" # read typ name into $h
		h="${h%%/*}"
		PAT="^...$h[0-9a-f]+$" # patternize
	fi
	# process "loc" changes
	if [[ "$d" = config/loc/* ]] ; then
		h="${d##config/loc/}" # read loc name into $h
		h="${h%%/*}"
		PAT="^$h...[0-9a-f]+$" # patternize
	fi
	# process "loc" = "pro" changes
	# because loc/pro is an artifical that does not match hostnames we have to generate extra patterns here
	if [[ "$d" = config/loc/pro/* ]] ; then
		PAT="^(ber|ham)...[0-9a-f]+$" # patternize
	fi
	# process "loctyp" changes
	if [[ "$d" = config/loctyp/* ]] ; then
		h="${d##config/loctyp/}" # read loctype name into $h
		h="${h%%/*}"
	        # because loctyp/pro... is an artifical that does not match hostnames we have to generate extra patterns here
		h="${h/pro/(ber|ham)}"
		PAT="^$h[0-9a-f]+$" # patternize
	fi
	# add it to the PATTERN
	if [ -n "$PAT" ] ; then
		if [ -z "$PATTERN" ] ; then
			PATTERN="$PAT"
		else
			PATTERN="$PATTERN
$PAT"
		fi
	fi
done

# unique pattern
PATTERN="$(sort -u <<<"$PATTERN")"
log "PATTERN '$PATTERN'"


# set to empty array if no config changed (and thus PATTERN is empty)
# this will be evaluated later to not build any RPMs
if [ -z "$PATTERN" ] ; then
	AFFECTED_HOSTS=()
else
	AFFECTED_HOSTS=($(grep -E "$PATTERN" <<<"$ALL_HOSTS" | sort -u))
fi

WORK=$($MKTEMP_CMD -p /dev/shm -t -d "$(basename "$0").XXXXXXXXXX")
trap "${KEEPWORKDIR:+echo Please do not forget to} rm -Rf $WORK $CONFIG_VIEWER/hosts/*.new 1>&2" 0

############ hostLookup function
#
# lookup hosts in NSS hosts database

function hostLookup() {
    local h="$1" ; shift
    if ! [[ "$h" ]] ; then
        die "hostLookup() called without argument"
    fi

    if [[ "$CUSTOM_DNS_SEARCHLIST" ]] ; then
        for suffix in "${CUSTOM_DNS_SEARCHLIST[@]}" ; do
            if getent hosts "$h"."$suffix" ; then
                return
            fi
        done
    else
        getent hosts "$h"
    fi
}
	
############ buildHost function
#
# do everything we need to do for a single host
# all files/dirs that this function changes need to be host-specific (e.g. with the hostname in it) 
# so that this function can run in parallel for different hosts.
#
function buildHost() {
	h="$1"
	# determine location and type from name LOCTYPNUM
	loc=${h:0:3}
	typ=${h:3:3}
	loctyp=${h:0:6}
    hostnr=${h:6}
	log "Building for host $h, typ $typ, loc $loc, loctype $loctyp, hostnr $hostnr"

	REQUIRES=""
	PROVIDES=""

	# create work space where we collect the config files from SVN
	# by exporting the different SVN paths on top of each other in the same 
	# work space we get the overlaying

	# we build a tar.gz that is suitable for rpmbuild -tb
	HOST_CONFIG="$WORK/$CONFIG_RPM_PREFIX-$h"
	mkdir "$HOST_CONFIG" || die "ERROR: '$HOST_CONFIG' exists already whereas I should be creating it now"
	SVN_PATHS=()
	echo >$WORK/$h.svnlog
	$SVN_CMD export -r $REV file:///"$REPOS"/config/all/ "$HOST_CONFIG"/ --force | sed -e "s#^.*is24-config-$h#all:1:#" >>$WORK/$h.svnlog
	if test $PIPESTATUS = 0 ; then
		SVN_PATHS=( "${SVN_PATHS[@]}" config/all )
		concatDependencies "REQUIRES" "$HOST_CONFIG/VARIABLES/RPM_REQUIRES"
		concatDependencies "PROVIDES" "$HOST_CONFIG/VARIABLES/RPM_PROVIDES"
	fi
	$SVN_CMD export -r $REV file:///"$REPOS"/config/typ/$typ/ "$HOST_CONFIG"/ --force  | sed -e "s#^.*is24-config-$h#typ/$typ:2:#" >>$WORK/$h.svnlog
	if test $PIPESTATUS = 0 ; then
		SVN_PATHS=( "${SVN_PATHS[@]}" "config/typ/$typ")
		concatDependencies "REQUIRES" "$HOST_CONFIG/VARIABLES/RPM_REQUIRES"
		concatDependencies "PROVIDES" "$HOST_CONFIG/VARIABLES/RPM_PROVIDES"
	fi
	# provide global production config possibilities before the concrete locations
	LOC_IS_PRO=0
	if test "$loc" = "ham" -o "$loc" = "ber" ; then
		LOC_IS_PRO=1
	fi
	if test "$LOC_IS_PRO" = "1" ; then
		$SVN_CMD export -r $REV file:///"$REPOS"/config/loc/pro/ "$HOST_CONFIG"/ --force  | sed -e "s#^.*is24-config-$h#loc/pro:3:#" >>$WORK/$h.svnlog
		if test $PIPESTATUS = 0 ; then
			SVN_PATHS=( "${SVN_PATHS[@]}" "config/loc/pro")
			concatDependencies "REQUIRES" "$HOST_CONFIG/VARIABLES/RPM_REQUIRES"
			concatDependencies "PROVIDES" "$HOST_CONFIG/VARIABLES/RPM_PROVIDES"
		fi
	fi

	$SVN_CMD export -r $REV file:///"$REPOS"/config/loc/$loc/ "$HOST_CONFIG"/ --force  | sed -e "s#^.*is24-config-$h#loc/$loc:4:#" >>$WORK/$h.svnlog
	if test $PIPESTATUS = 0 ; then
		SVN_PATHS=( "${SVN_PATHS[@]}" "config/loc/$loc")
		concatDependencies "REQUIRES" "$HOST_CONFIG/VARIABLES/RPM_REQUIRES"
		concatDependencies "PROVIDES" "$HOST_CONFIG/VARIABLES/RPM_PROVIDES"
	fi
	if test "$LOC_IS_PRO" = "1" ; then
		$SVN_CMD export -r $REV file:///"$REPOS"/config/loctyp/pro$typ/ "$HOST_CONFIG"/ --force  | sed -e "s#^.*is24-config-$h#loctyp/pro$typ:5:#" >>$WORK/$h.svnlog
		if test $PIPESTATUS = 0 ; then
			SVN_PATHS=( "${SVN_PATHS[@]}" "config/loctyp/pro$typ")
			concatDependencies "REQUIRES" "$HOST_CONFIG/VARIABLES/RPM_REQUIRES"
			concatDependencies "PROVIDES" "$HOST_CONFIG/VARIABLES/RPM_PROVIDES"
		fi
	fi
	$SVN_CMD export -r $REV file:///"$REPOS"/config/loctyp/$loctyp/ "$HOST_CONFIG"/ --force  | sed -e "s#^.*is24-config-$h#loctyp/$loctyp:6:#" >>$WORK/$h.svnlog
	if test $PIPESTATUS = 0 ; then
		SVN_PATHS=( "${SVN_PATHS[@]}" "config/loctyp/$loctyp")
		concatDependencies "REQUIRES" "$HOST_CONFIG/VARIABLES/RPM_REQUIRES"
		concatDependencies "PROVIDES" "$HOST_CONFIG/VARIABLES/RPM_PROVIDES"
	fi
	$SVN_CMD export -r $REV file:///"$REPOS"/config/host/$h/ "$HOST_CONFIG"/ --force  | sed -e "s#^.*is24-config-$h#host/$h:7:#" >>$WORK/$h.svnlog
	if test $PIPESTATUS = 0 ; then
		SVN_PATHS=( "${SVN_PATHS[@]}" "config/host/$h")
		concatDependencies "REQUIRES" "$HOST_CONFIG/VARIABLES/RPM_REQUIRES"
		concatDependencies "PROVIDES" "$HOST_CONFIG/VARIABLES/RPM_PROVIDES"
	fi

	# process requires and provides
	REQUIRES=$($SCRIPTPATH/RPMDepend/Dependency/RPMDepend.py --collapseDuplicates <<<"$REQUIRES")
	PROVIDES=$($SCRIPTPATH/RPMDepend/Dependency/RPMDepend.py <<<"$PROVIDES")
	
 	# and write the processed data to files
	echo "$REQUIRES" > "$HOST_CONFIG/VARIABLES/RPM_REQUIRES" 
	echo "$PROVIDES" > "$HOST_CONFIG/VARIABLES/RPM_PROVIDES" 
	# debug output
    echo 1>&2 "Processed REQUIRES=<<<$REQUIRES>>>"
    echo 1>&2 "Processed PROVIDES=<<<$PROVIDES>>>"

    if [ "$REPO_PACKAGES_REGEX" ] ; then
        # split requires packages in repos and non-repos
        REQUIRES_REPOS=$($SCRIPTPATH/RPMDepend/Dependency/RPMDepend.py --filter "$REPO_PACKAGES_REGEX" <<<"$REQUIRES")
        REQUIRES_NON_REPOS=$($SCRIPTPATH/RPMDepend/Dependency/RPMDepend.py --negative --filter "$REPO_PACKAGES_REGEX" <<<"$REQUIRES")
        # and write the processed data to files
        echo "$REQUIRES_REPOS" > "$HOST_CONFIG/VARIABLES/RPM_REQUIRES_REPOS" 
        echo "$REQUIRES_NON_REPOS" > "$HOST_CONFIG/VARIABLES/RPM_REQUIRES_NON_REPOS"
        # debug output
        echo 1>&2 "Processed REQUIRES_REPOS=<<<$REQUIRES_REPOS>>>"
        echo 1>&2 "Processed REQUIRES_NON_REPOS=<<<$REQUIRES_NON_REPOS>>>"
    fi
    
	# get the SPEC template and add it into the work space
	$SVN_CMD export -r $REV file:///"$REPOS"/$CONFIG_SPEC "$HOST_CONFIG"/$CONFIG_RPM_PREFIX-$h.spec --force || die "Could not SVN export '$CONFIG_SPEC' for host '$h'"

	# add the last log entries to the SPEC file and patch up the SPEC file with the information we know already
	# NOTE: Here we don't use -r $REV because that would give us no history. We hope that there is situation
	# where adding -r $REV would yield a different result at the top of the log item list
	$SVN_CMD log -l 5 -v file://"$REPOS" "${SVN_PATHS[@]}" | sed -i -e "/^SVNLOG/r/dev/stdin" -e "s/HOST/$h/g" -e "s/REV/$REV/g" "$HOST_CONFIG"/$CONFIG_RPM_PREFIX-$h.spec

	# move VARIABLES subdir out of work space to keep it out of the RPM
	mv $HOST_CONFIG/VARIABLES $WORK/VARIABLES.$h || die "Could not mv $HOST_CONFIG/VARIABLES $WORK/VARIABLES.$h'"

	# list the overlaying source for each file. Use the svnlog with a revert sort trick to get only the last overlaying dir.
	# the numbers set above are sorting helpers and required to keep identical paths in the right order (using sort -u to only take the first line 
	# of several identical ones). In the end we remove the numbers from the output.
	file_overlaying_list="$(
		sort -r -u -k 2 -t : $WORK/$h.svnlog | sort -u -k 3 -t : | sed -e 's/:[0-9]:/:/'
	)"

	# convert technical list into nicely indented human readable list
	#
	file_overlaying_info="$(
		while IFS=: read key val ; do
			printf "%25s : %s\n" "$key" "$val"
		done <<<"$file_overlaying_list"
	)"
	
	# create file list of work space
	#  - remember it for the patcher
    # TODO: remove legacy code
	find "$HOST_CONFIG" -not -type d -printf "%P\n" >$WORK/filelist.$h 

    # modify the filelist for the patcher to contain full paths
	sed -i -e "s#^#$HOST_CONFIG/#" $WORK/filelist.$h || die "Could not patch $WORK/filelist.$h to contain full paths"

    # add hostname and other hostname-related stuff to VARIABLES
    echo $h > $WORK/VARIABLES.$h/HOST
    echo $loc > $WORK/VARIABLES.$h/LOC
    echo $typ >$WORK/VARIABLES.$h/TYP
    echo $loctyp >$WORK/VARIABLES.$h/LOCTYP
    echo $hostnr >$WORK/VARIABLES.$h/HOSTNR
    short_hostnr="$hostnr"
    while [[ "${short_hostnr:0:1}" == "0" ]] ; do short_hostnr="${short_hostnr:1}" ; done # strip leading 0
    echo "$short_hostnr" >$WORK/VARIABLES.$h/SHORT_HOSTNR

	# get FQDN and IP and ALIASES and add it to the VARIABLES
	# skip this part if we cannot resolve the host
    if read ip fqdn aliases < <(hostLookup "$h") ; then
        echo "$ip" >$WORK/VARIABLES.$h/IP
        echo "$fqdn" >$WORK/VARIABLES.$h/FQDN
        echo "$aliases" >$WORK/VARIABLES.$h/ALIASES
    elif test -z "$ALLOW_UNKNOWN_HOSTS" ; then
        # if we do not allow unknown hosts then fail
        die "Could not lookup '$h' with 'getent hosts'"
    else
        echo "127.0.0.1" >$WORK/VARIABLES.$h/IP
        echo "localhost.localdomain" >$WORK/VARIABLES.$h/FQDN
        echo "" >$WORK/VARIABLES.$h/ALIASES
    fi

	# create sed command script for patcher
	echo >$WORK/patcher.$h
	for f in $WORK/VARIABLES.$h/* ; do
		read -r < "$f" # read first line into $REPLY TODO: read entire file but drop last LF
		f=${f##*/} # basename
		REPLY="${REPLY//#/\\#}" # escape "#" in variable data not to confuse s### in sed command line
		echo "s#@@@$f@@@#$REPLY#g" >>$WORK/patcher.$h
	done

	# write out patcher data to spec file description area. The result looks like this:
	#         COL_HOST : col.arc.int
	#      DB_IBW_HOST : db.arc.int
	#    DB_TERMS_HOST : db.arc.int
	# DB_TERMS_RO_HOST : db.arc.int
	#       EMAIL_HOST : system.arc.int
	#     RPM_PROVIDES :
	#     RPM_REQUIRES : is24-configserver is24-deploydaemon-server
	#      SYSLOG_HOST : system.arc.int
	#               IP : 10.100.201.60
	#             FQDN : tuvdep01.arc.int
	#          ALIASES :

	patch_info="$(
		sed -ne 's/s#@@@\(.*\)@@@#\(.*\)#g/\1:\2/p' <$WORK/patcher.$h | while IFS=: read key val ; do 
			printf "%40s : %s\n" "$key" "$val"
		done
	)"

	# add variable:content info to spec file under VARIABLES
	echo "$patch_info" | sed -i -e "/^VARIABLES/r/dev/stdin" "$HOST_CONFIG"/$CONFIG_RPM_PREFIX-$h.spec
	# add overlay report to spec file under OVERLAYING
	echo "$file_overlaying_info" | sed -i -e "/^OVERLAYING/r/dev/stdin" "$HOST_CONFIG"/$CONFIG_RPM_PREFIX-$h.spec

	# copy files in workspace to CONFIG_VIEWER
	# we need to copy the files here before they will be patched for the RPM!!
	# remove destination folder to make sure that there are no old left-overs
	[ ! -e "$CONFIG_VIEWER/hosts/$h.new" ] || rm -Rf "$CONFIG_VIEWER/hosts/$h.new" || die "Could not remove '$CONFIG_VIEWER/hosts/$h.new'"
	mkdir -p "$CONFIG_VIEWER/hosts/$h.new" || die "Could not mkdir '$CONFIG_VIEWER/hosts/$h.new'"
	tar -C "$HOST_CONFIG" -c . | tar -C "$CONFIG_VIEWER/hosts/$h.new" -x || die "Could not copy '$HOST_CONFIG' to '$CONFIG_VIEWER/hosts/$h.new' with tar"
	cp -r "$WORK/VARIABLES.$h" "$CONFIG_VIEWER/hosts/$h.new/VARIABLES" || die "Could not copy '$WORK/VARIABLES.$h' to '$CONFIG_VIEWER/hosts/$h.new/VARIABLES'"

	# Execute token_replacer in $HOST_CONFIG with variable definition read from VARIABLES.$h
    if ! PYTHONPATH=$SCRIPTPATH/libs/src/main/python/ $SCRIPTPATH/libs/src/main/scripts/filter-tokens-in-rpm-sources $HOST_CONFIG $WORK/VARIABLES.$h ; then
        echo "ERROR: Variable substitution failed, aborting.

The following tokens are defined:
$patch_info" | tr -c '[:graph:][:space:]' '?' 1>&2
		# this tr hack is unbelievably ugly and the only way I found as a quick hack 
		# around http://subversion.tigris.org/issues/show_bug.cgi?id=2487
		# The issue is that if there are any non-latin1 characters in the error output
		# then the svn client will complain about not beeing able to convert the output
		# to utf8 and not display it. [Bang your head here]
		#
		# Bottom line, add whatever problematic chars to the tr list and explain to users
		# that the output is not 100% the same as in the files.
		exit 1
	fi

	# pack work space into tar.gz and build RPM
	tar -c -v -z -f "$HOST_CONFIG".tar.gz -C "$WORK" $CONFIG_RPM_PREFIX-$h
	mkdir -p $WORK/rpmbuild/{tmp,RPMS,RPMS/x86_64,RPMS/noarch,BUILD,SRPMS,SPECS,SOURCES}
	HOME=$WORK rpmbuild --define="_topdir $WORK/rpmbuild" -ta "$HOST_CONFIG".tar.gz 1>&2 || die "Could not build RPM for host '$h'"

	# store file overlaying list and patch info for config viewer
	echo "$file_overlaying_list" >$CONFIG_VIEWER/hosts/$h.new/$h.overlaying || die "Could not write overlaying list file '$CONFIG_VIEWER/hosts/$h.new/$h.overlaying'"
	echo "$patch_info" >$CONFIG_VIEWER/hosts/$h.new/$h.variables || die "Could not write patch_info file '$CONFIG_VIEWER/hosts/$h.new/$h.variables'"
	# put revision file 
	echo "$REV" >$CONFIG_VIEWER/hosts/$h.new/$h.rev || die "Could not write revision file '$CONFIG_VIEWER/hosts/$h.new/$h.rev'"

	# patch all files in CONFIG_VIEWER host space, fixup filelist to point to files in CONFIG_VIEWER host space
	# we add $h.variables and $h.rev to the list of files to be patched to convert it also to HTML
	PYTHONPATH=$SCRIPTPATH/libs/src/main/python/ $SCRIPTPATH/libs/src/main/scripts/filter-tokens-in-configviewer-sources $CONFIG_VIEWER/hosts/$h.new $WORK/VARIABLES.$h
	for f in $(sed -e "s#^$HOST_CONFIG#$CONFIG_VIEWER/hosts/$h.new#" "$WORK/filelist.$h" <(echo -e "$HOST_CONFIG/$h.variables" ))
	do
        file_content=$(sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g' -e 's#-ltrepme-#<#g' -e 's#-gtrepme-#>#g' "$f")
        #file_content=$(< "$f")
		echo "<!DOCTYPE html><html><head><title>$(basename $f)</title></head><body><pre>$file_content</pre></body></html>" > $f
	done
} # end buildHost

# process hosts in parallel
let processed=0
let start_time=SECONDS

while [ "$processed" -lt "${#AFFECTED_HOSTS[@]}" ] ; do
	# take PARALLELISATION sized chunk out of AFFECTED_HOSTS from the $processed position
        TAKE_HOSTS=( ${AFFECTED_HOSTS[@]:$processed:$PARALLELISATION} )
        PIDS=()
        for h in ${TAKE_HOSTS[@]} ; do
                buildHost "$h" >$WORK/$h.output 2>&1 &
		# remember the PIDs of the background tasks, format is PID:HOST, like 234234:devbas03
                PIDS=( "${PIDS[@]}" "$!:$h" )
        done
	# check the result of each PIDs
	let errors=0
        for p in "${PIDS[@]}" ; do
                IFS=: read pid h junk <<<"$p" 
                if wait $pid ; then
			log "Successfully built for '$h'"
		else
                        log "Failed to build RPM for $h"
			# take everything from the buildHost output starting from the first occurance of ERROR
			# patch host: into each line of error file
			sed -n -e "/ERROR/I,\$s/^/$h: /p" $WORK/$h.output >$WORK/$h.error
			let errors++
                fi
        done
        let processed=processed+PARALLELISATION
	# if there where errors in this chunk of hosts don't even try to do the next chunk
	if [ "$errors" -gt 0 ] ; then
		break
	fi
done
log "Processed ${#AFFECTED_HOSTS[@]} hosts in $((SECONDS-start_time)) seconds"

# collect and display errors from host building
ERROR_FILES=( $WORK/*.error )
if test "$ERROR_FILES" ; then
    mkdir -p "$CONFIG_VIEWER"/errors
    {
	echo "ERROR: At least one host has a configuration error:"
	for efile in "${ERROR_FILES[@]}" ; do
		echo 
		cat "$efile"
	done
	cat <<-EOF

	Your commit as been accepted by the SVN server, but due to the
	errors that it contains no RPMs have been created.

	Please fix the issues and trigger the RPM creation with a dummy commit.

EOF
    } >"$CONFIG_VIEWER"/errors/"$REV".txt
    cat <<-EOF

ERROR: At least one host has a configuration error.

Your commit as been accepted by the SVN server, but due to the
errors that it contains no RPMs have been created.

See $CONFIG_VIEWER_URL/errors/$REV.txt for details.

Please fix the issues and trigger the RPM creation with a dummy commit.

EOF
	exit 1
fi 1>&2
	
# allow anybody to cd into the workdir, needed for putinrepo
chmod +x $WORK

if test "$AFFECTED_HOSTS" ; then
	# move RPMs only if we had some hosts to work on
	let start_time=SECONDS
	if [[ "$REPOTARGET" ]] ; then
		if [[ "$REPOTARGET" == *://* ]] ; then
			if [[ "$REPOTARGET" != */ ]] ; then
				# REPO must have a trailing /
    			REPOTARGET="$REPOTARGET/"
			fi
			for package in $WORK/rpmbuild/RPMS/*/*.rpm $WORK/rpmbuild/SRPMS/*.rpm ; do
			    if ! res=$( curl "${REPOTARGET_CURL_OPTIONS[@]}" -sSf --data-binary @"$package" "$REPOTARGET" 2>&1) ; then
			        die "Could not upload '$package' to '$REPOTARGET': $res"
			    fi
			done
		else
			$REPOTARGET/putinrepo $WORK/rpmbuild/RPMS/*/*.rpm $WORK/rpmbuild/SRPMS/*.rpm || die "Could not add RPMs to $REPOTARGET via $REPOTARGET/putinrepo"
		fi
	fi
	log "Added to $REPOTARGET in $((SECONDS-start_time)) seconds:" $WORK/rpmbuild/RPMS/*/*.rpm $WORK/rpmbuild/SRPMS/*.rpm

	# add new build result to CONFIG_VIEWER
	let start_time=SECONDS
	for h in "${AFFECTED_HOSTS[@]}" ; do
		HOST_CONFIG="$WORK/$CONFIG_RPM_PREFIX-$h"
		# remove spec file
		# TODO: find out why this should be removed, I think it is just wrong and makes debugging more difficult. I disabled it for now and we shall see.
        # Schlomo 2012-01-16
        ### rm -f "$HOST_CONFIG"/$CONFIG_RPM_PREFIX-$h.spec || die "Could not remove '$HOST_CONFIG/$CONFIG_RPM_PREFIX-$h.spec'"
		rm -Rf $CONFIG_VIEWER/hosts/$h || die "Could not remove '$CONFIG_VIEWER/hosts/$h'"
		mv -v $CONFIG_VIEWER/hosts/$h.new $CONFIG_VIEWER/hosts/$h || die "Could not move '$CONFIG_VIEWER/hosts/$h.new' '$CONFIG_VIEWER/hosts/$h'"
		# pack config tree for tar.gz export, to beautify the tar.gz we use find. Because of %P the first line of
		# the find result is empty and confuses tar, so we remove it with sed
		# Broken on Ubuntu
		#find "$HOST_CONFIG" -printf "%P\n" | sed -e '1d' | tar -czf $CONFIG_VIEWER/hosts/$h.tar.gz -T - -C  "$HOST_CONFIG" \
		#	|| die "Could not create '$CONFIG_VIEWER/hosts/$h.tar.gz' with tar"
	done
	log "Updated configviewer ($CONFIG_VIEWER) in $((SECONDS-start_time)) seconds"

else
	log "No configuration files changed, did not build any RPMs"
fi

log "Total execution time is $SECONDS seconds"
declare -p DIRS_CHANGED PATTERN AFFECTED_HOSTS 1>&2
exit 0
